package org.hzero.oauth;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpCallExample {
    public static void main(String[] args) {
        Map<String, Object> results = new HashMap<>();
        results.put("grant_type", "client_credentials");
        results.put("client_id", "hzero-front-dev");
        results.put("password", "c2VjcmV0");

        String url = "http://localhost:8080/oauth/oauth/token";
        try {
            String response = sendPostRequest(url, results);
            System.out.println("响应内容: " + response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String sendPostRequest(String url, Map<String, Object> params) throws IOException {
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);

        List<NameValuePair> paramList = new ArrayList<>();
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            paramList.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
        }

        httpPost.setEntity(new UrlEncodedFormEntity(paramList, "UTF-8"));

        HttpResponse response = httpClient.execute(httpPost);
        return EntityUtils.toString(response.getEntity(), "UTF-8");
    }
}
